package com.base.util.javautils.observer;

import android.support.annotation.NonNull;

import java.util.ArrayList;
import java.util.List;

public class ObservableForMainThread implements IObservable {

    private boolean m_bIsNextNotify;
    protected final List<IObserver> mObservers = new ArrayList<>();

    @Override
    public void notifyObservers() {
        notifyObservers(new ObserverGeneralMessage(ObserverMessageGeneralType.SUCCESS));
    }

    @Override
    public void notifyObservers(@NonNull AbstractObserverMessage data) {
        m_bIsNextNotify = true;
        Object[] array = mObservers.toArray();
        for (int i = 0; i < array.length; ++i) {
            if (m_bIsNextNotify) {
                ((IObserver) array[i]).update(this, data);
            }
        }
        m_bIsNextNotify = false;
    }

    @Override
    public void registerObserver(@NonNull IObserver observer) {
        mObservers.add(observer);
    }

    @Override
    public void unregisterObserver(@NonNull IObserver observer) {
        for (int i = 0; i < mObservers.size(); ++i) {
            if (observer.equals(mObservers.get(i))) {
                mObservers.remove(i);
                break;
            }
        }
    }

    @Override
    public void cancelNextNotify() {
        m_bIsNextNotify = true;
    }

    @Override
    public void deleteObservers() {
        mObservers.clear();
    }

    @Override
    public int countObservers() {
        return mObservers.size();
    }
}
